package main

import (
	"fmt"
	"gopkg.in/mgo.v2"
	"log"
	"strconv"
	"strings"
)

//创建数据类型
type Person struct {
	Name string
}

//main函数
func main() {
	address, username, password := "10.128.137.43:60039", "mongo_user", "a8e1cc357a377f9766e9051de66e76f9"
	//插入数据
	err := InsertData(address, username, password, "admin")
	if err != nil {
		log.Printf("InsertData: Fail to insert data: %s\n", err)
	}
	//查找primary节点
	err = FindPrimary(address, username, password, "admin")
	if err != nil {
		log.Printf("FindPrimary: Fail to insert data: %s\n", err)
	}
	//查找数据
	err = FindData(address, username, password, "admin")
	if err != nil {
		log.Printf("FindData: Fail to insert data: %s\n", err)
	}
}

//插入数据的InsertData函数
func InsertData(address, username, password, database string) error {
	var link string
	link = "mongodb://" + username + ":" + password + "@" + address + "/" + database
	//连接到mongo
	session, err := mgo.Dial(link)
	if err != nil {
		return err
	}
	if session == nil {
		err = fmt.Errorf("InsertData: Dial: session is nil")
		return err
	}
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)
	c := session.DB(database).C("testCo")
	for i := 1; i <= 1000; i++ {
		err = c.Insert(&Person{"number" + strconv.Itoa(i)})
		if err != nil {
			return err
		}
	}
	log.Println("InsertData: Insert datas completely")
	return nil
}

//寻找primary节点的FindPrimary函数
func FindPrimary(address, username, password, database string) error {
	addresses := strings.Split(address, ",")
	for _, ad := range addresses {
		link := "mongodb://" + username + ":" + password + "@" + ad + "/" + database
		//连接到mongo
		session, err := mgo.Dial(link)
		if err != nil {
			log.Printf("FindPrimary: %s", err)
			continue
		} else {
			log.Printf("FindPrimary: Now the primary point's address is: [ %s ]\n", ad)
			session.Close()
			return nil
		}
		if session == nil {
			log.Printf("FindPrimary: Dial: [ %s ] session is nil\n", ad)
			continue
		}
	}
	err := fmt.Errorf("FindPrimary: Please keep one mongo point on at least")
	return err
}

//查找数据的FindData函数
func FindData(address, username, password, database string) error {
	var link string
	var people []Person
	link = "mongodb://" + username + ":" + password + "@" + address + "/" + database
	//连接到mongo
	session, err := mgo.Dial(link)
	if err != nil {
		return err
	}
	if session == nil {
		err = fmt.Errorf("FindData: Dial: session is nil")
		return err
	}
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)
	c := session.DB(database).C("testCo")
	err = c.Find(nil).All(&people)
	if err != nil {
		log.Println("FindData: Failed to find data")
		return err
	} else {
		log.Printf("FindData: find [ %d ] data successfully\n", len(people))
	}
	return nil
}
